package cn.shop.ylp.controll;

import cn.shop.ylp.Auth;
import cn.shop.ylp.AuthMapper;
import cn.shop.ylp.User;
import cn.shop.ylp.UserMapper;
import cn.shop.ylp.error.BussinessException;
import cn.shop.ylp.error.CommonReturnType;
import cn.shop.ylp.error.EmBussinessError;
import cn.shop.ylp.validator.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author yulianpeng
 * @email network_u@163.com
 * Date 2020/9/9
 */
@Controller
@RequestMapping("/user")
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class Login extends BaseController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ValidatorImpl validator ;
    @Autowired
    private AuthMapper authMapper;
    @RequestMapping(value = "/login",method = {RequestMethod.POST})
    @ResponseBody
    public CommonReturnType login(@RequestParam(name = "telphone") String phone, @RequestParam(name="password") String pd, HttpServletRequest request)
        throws BussinessException{
        User user = new User();
        user.setPhone(phone);
        user.setPd(pd);
        ValidationResult vResult = validator.validate(user);
        if (vResult.isHasErrors()){
            throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR,vResult.getErrMsg());
        }
        user = userMapper.selectByPhoneAndPd(phone, pd);
        if (user==null){
            throw new BussinessException(EmBussinessError.USER_LOGIN_FAILURE);
        }
        //登录成功
//        String uuid = UUID.randomUUID().toString();
//        uuid = uuid.replace("-","");
//        Cookie cookie = new Cookie("id",uuid);
        //已经登录更新
        Auth auth = authMapper.selectByPrimaryKey(user.getId());

        if (auth==null){
            auth = new Auth();
            //插入
            auth.setId(user.getId());
            auth.setSession(getSessionId(request));
            authMapper.insert(auth);
        } else {
            auth.setSession(getSessionId(request));
            authMapper.updateByPrimaryKey(auth);
        }
        return CommonReturnType.create(null);
    }
    @RequestMapping(value = "/register",method = {RequestMethod.POST})
    @ResponseBody
    public CommonReturnType register(@RequestParam(name = "telphone") String phone, @RequestParam(name="password") String pd) throws UnsupportedEncodingException, NoSuchAlgorithmException, BussinessException {
        // 验证参数
        User user = new User();
        user.setPhone(phone);
        user.setPd(pd);
        ValidationResult result = validator.validate(user);
        if (result.isHasErrors() || user==null){
            throw new BussinessException(EmBussinessError.PARAMETER_VALIDATION_ERROR,result.getErrMsg());
        }
        if(userMapper.selectByPhone(phone)!=null){
            //已注册，请登录
            throw new BussinessException(EmBussinessError.USER_EXIST);
        }
        if(userMapper.insertSelective(user)<=0){
            throw new BussinessException(EmBussinessError.UNKNOWN_ERROR,result.getErrMsg());
        }
        return CommonReturnType.create(null);
    }
    @RequestMapping(value = "/user",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType getUser(HttpServletRequest request){
        User user = getUserBySession(request);
        if (user!=null){
            return CommonReturnType.create(user);
        }
        return CommonReturnType.create(null,"error");

    }
    public User getUserBySession(HttpServletRequest request){
        HttpSession session = request.getSession();
        String sid = session.getId();
        Auth auth = authMapper.selectByUuid(sid);
        if (auth==null){
            return null;
        }
        return userMapper.selectByPrimaryKey(auth.getId());
    }
    public String getSessionId(HttpServletRequest request){
        HttpSession session = request.getSession();
        String sid = session.getId();
        return sid;
    }

}
